package MTProxyServer;

import java.io.*;
import java.net.*;
import java.util.*;

public class Server
{
	// The ServerSocket we'll use for accepting new connections
	private ServerSocket ss;

	private static Server mServer = null;
	
	public static Server GetInstance()
	{
		if( null == mServer){
			mServer = new Server();
		}
		return mServer;
	}

	// Constructor and while-accept loop all in one.
	public Server()
	{
	}
	
	public synchronized  void Listen( int port ) throws IOException 
	{
		// Create the ServerSocket
		//System.out.println( "Host:" + InetAddress.getByName( "localhost" ).toString() );
		if( MTConstant.MT_TCP_IS_LOCALHOST ){
			ss = new ServerSocket( port, 50 , InetAddress.getByName( "localhost" ) );
		}
		else{
			ss = new ServerSocket( port, 50 , InetAddress.getLocalHost() );
		}
		
		// Tell the world we're ready to go
		System.out.println( "Listening on "+ss );
		
		//System.out.println( " Server Socket IP " + ss.getInetAddress().toString() );
		//System.out.println( " getLocalSocketAddress " + ss.getLocalSocketAddress().toString() );
		
		
		// Keep accepting connections forever
		while (true) {
			// Grab the next incoming connection
			Socket s = ss.accept();
			// Tell the world we've got it
			System.out.println( "Connection from "+s );
			
			new ServerThread( this, s );
		}
	}
	
	// Main routine
	// Usage: java Server <port>
	static public void main( String args[] ) throws Exception {
		// Get the port # from the command line
		//int port = Integer.parseInt( args[0] );
		SQLManager.SQLManager.GetInstance();
		
		System.out.println("Local Host:" + InetAddress.getLocalHost() );
		
		// Create a Server object, which will automatically begin
		// accepting connections.
		Server.GetInstance().Listen( MTConstant.MT_PORT );
		
		
		
	}
	
	protected void finalize() throws Throwable 
	{  
	    super.finalize();
	    ss.close();
	    System.out.println( "Server is closed.");
	}
}
